package com.victor9ac.tfm.mashup.connector.adapter.spring.restTemplate;

import java.net.URI;
import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.victor9ac.tfm.mashup.connector.exception.MashupConnectionException;
import com.victor9ac.tfm.mashup.connector.port.MashupConnector;
import com.victor9ac.tfm.mashup.uris.ConnectionBean;
import com.victor9ac.tfm.mashup.uris.MashupURIFactory;

public class MashupConnectorRestTemplate implements MashupConnector {

	protected RestTemplate restTemplate;
	protected ConnectionBean connectionBean;
	protected String resourceContext;

	//instances as a singleton
	MashupURIFactory uriFactory;

	public MashupConnectorRestTemplate() {
		super();

	}
	public MashupConnectorRestTemplate(String resourceContext) {
		this.resourceContext = resourceContext;

	}


	public <T> T get(String resource, Class<T> classGiven)
			throws MashupConnectionException {
		T result = execute(resource, classGiven);
		return result;
	}
	

	@Async
	public <T> Future<T> asyncGet(String resource, Class<T> classGiven)
			throws MashupConnectionException {

		AsyncResult<T> result = null;
		T obj = execute(resource, classGiven);
		result = new AsyncResult<T>(obj);
		
		return result;
	}

	private <T> T execute(String resource, Class<T> classGiven)
			throws MashupConnectionException {
		T result = null;
		long ini = System.currentTimeMillis();
		try {
			URI uri = getUri(resource);
			System.out.println("uri built: "+uri);
			result = restTemplate.getForObject(uri, classGiven);
		} catch (RestClientException e) {
			System.out.println("error getting ws info");
			e.printStackTrace();

		} catch (Exception e) {
			System.out.println("unknow error");
			e.printStackTrace();
			throw new MashupConnectionException(e);
		}
		System.out.println("> get elapsed..("+classGiven.getSimpleName()+"): "+(System.currentTimeMillis()-ini));
		return result;
	}
	protected URI getUri(String resource) {
		return new MashupURIFactory(this.connectionBean, this.resourceContext, resource).getUri();
	}



	public void setRestTemplate(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}
	public void setConnectionBean(ConnectionBean connectionBean) {
		this.connectionBean = connectionBean;
	}
	public void setResourceContext(String resourceContext) {
		this.resourceContext = resourceContext;
	}
}
